/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed under the Apache license, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.internna.iwebjtracker.spring.mvc;

import org.internna.iwebmvc.model.User;
import org.internna.iwebmvc.utils.Assert;
import org.internna.iwebmvc.dao.SecurityDAO;
import org.internna.iwebmvc.crypto.Decipherer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Activates an account disabled by default.
 *
 * @author Jose Noheda
 * @since 1.0
 */
@Controller
@RequestMapping(AccountActivationController.ACTIVATION_PATH)
public final class AccountActivationController {

    /**
     * Path where the account activation controller listens to incoming requests.
     */
    public static final String ACTIVATION_PATH = "/emailconfirmation.iwebmvc";

    private Decipherer decipherer;
    private SecurityDAO securityDAO;

    /**
     * Spring injection point (REQUIRED)
     *
     * @param securityDAO a not null instance
     */
    @Required public void setSecurityDAO(SecurityDAO securityDAO) {
        Assert.notNull(securityDAO);
        this.securityDAO = securityDAO;
    }

    /**
     * Spring injection point (REQUIRED)
     *
     * @param decipherer a not null implementation
     */
    @Required public void setDecipherer(Decipherer decipherer) {
        Assert.notNull(decipherer);
        this.decipherer = decipherer;
    }

    /**
     * Gets the username and activates the user logins.
     *
     * @param data provided by the "data" URL parameter
     *
     * @return redirect:/index.iwebmvc
     */
    @RequestMapping(method = RequestMethod.GET)
    public String rss(@RequestParam(value = "data", required = true) String data) {
        Assert.isEncrypted(decipherer, data);
        String usernameEmail = decipherer.decrypt(data);
        User existing = securityDAO.findUser(usernameEmail.substring(0, usernameEmail.indexOf('#')));
        if (existing != null) {
            existing.toggle();
            securityDAO.updateUser(existing);
        }
        return "redirect:/index.iwebmvc";
    }

}
